var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

const session = require('express-session')
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views')); // 设置ejs为模板引擎
app.set('view engine', 'ejs');

app.use(logger('dev')); // 记录请求
app.use(express.json());
app.use(express.urlencoded({ extended: false })); // 解析post请求
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); // 设置静态目录

// 注册session
app.use(session({
    name:'zy',
    secret:'sss',
    cookie: {
      maxAge:1000*60*60,
      secure:false
    },
    resave:true,
    saveUninitialized:true,
}))
// 设置中间件，session校验
app.use((req,res,next) => {
  console.log(req.url)
  if(req.session.user || req.url == '/login' || req.url == '/') {
    next()
  } else {
    // 是接口返回错误码
    // 不是接口，重定向
    // 我这里接口和返回页面未分离
    res.redirect('/')
  }
})

app.use('/', indexRouter); // 路由级别中间件
app.use('/api', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) { // 404错误中间件
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message; // locals是上下文对象
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
